package org.example.n2n;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Set;

/**
 * @author zhaokuii11@163.com
 * @create 2021-12-06 17:04
 * @Description
 */
public class Demo1 {
    private SessionFactory sessionFactory;//会话工厂
    private Session session;//会话
    private Transaction transaction;//事务

    @Before //juint测试方法 之前执行
    public void init() {
        System.out.println("init");
        //1. 根据 Configuration创建 会话工厂
        sessionFactory = new Configuration().configure().buildSessionFactory();
        //2. 创建 会话
        session = sessionFactory.openSession();
        //3. 创建事务
        transaction = session.beginTransaction();
    }


    @Test
    public void testGet() {
        //支持懒加载
        Category category = session.get(Category.class, 1);
        System.out.println(category.getName());
        Set<Item> item = category.getItem();
        //需要连接中间表
        System.out.println(item.size());
    }

    @Test
    public void testSave() {
        //设定关联关系
        Category category1 = new Category(null, "cay-AA");
        Category category2 = new Category(null, "cay-BB");
        Item item1 = new Item(null, "item-AA");
        Item item2 = new Item(null, "item-BB");
        category1.getItem().add(item1);
        category2.getItem().add(item2);
        item1.getCategories().add(category1);
        item1.getCategories().add(category2);

        item2.getCategories().add(category1);
        item2.getCategories().add(category2);
        //保存
        //插入4条记录 tab_category  tab_item tab_category_item
        session.save(category1);
        session.save(category2);
        session.save(item1);
        session.save(item2);
    }

    @After//juint测试方法 之后执行
    public void destroy() {
        //先开后关
        System.out.println("destroy");
        transaction.commit();
        session.close();
        sessionFactory.close();
    }
}
